﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;

namespace 代码生成器偶也
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public DataTable ExecuteDataTable(string cmdText,
            params SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(txtConnStr.Text))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = cmdText;
                    cmd.Parameters.AddRange(parameters);
                    DataTable dt = new DataTable();
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(dt);
                    return dt;
                }
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            DataTable dt = ExecuteDataTable("select * from INFORMATION_SCHEMA.TABLES");
            foreach (DataRow row in dt.Rows)
            {
                string tablename = (string)row["TABLE_NAME"];
                clbTables.Items.Add(tablename);
            }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            foreach (string tablename in clbTables.CheckedItems)
            {
                DataTable dtCols = ExecuteDataTable("select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@tablename",
                    new SqlParameter("tablename",tablename));
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("class Person");
                sb.AppendLine("{");
                foreach (DataRow row in dtCols.Rows)
                {
                    string colName = (string)row["Column_Name"];
                    string dataType = (string)row["Data_Type"];

                    sb.AppendLine("public "+dataType+" "+colName+" { get; set; }");
                    //MessageBox.Show((string)row["Column_Name"]+(string)row["Data_Type"]);
                }
                sb.AppendLine("}");
                MessageBox.Show(sb.ToString());
                File.WriteAllText(@"c:\"+tablename+".cs",sb.ToString());
            }
        }
    }
}
